<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
        }

        .container {
            width: 500px;
            height: 500px;
            border: 1px solid;
            position: relative;
            margin: auto;
        }

        .box {
            width: 100px;
            height: 100px;
            position: absolute;
            animation: ani ease-out 1s infinite;
            border-radius: 5px;
        }

        @keyframes ani {
            from {
                background-image: repeating-linear-gradient(135deg, rgba(255, 255, 255, .5) 0, rgba(255, 255, 255, .5) 10px, rgba(0, 255, 0, 0.5) 10px, rgba(0, 255, 0, 0.5) 20px),
                    repeating-linear-gradient(45deg, rgba(0, 255, 0, 0.5) 0, rgba(0, 255, 0, 0.5) 10px, rgba(255, 255, 255, .5) 10px, rgba(255, 255, 255, .5) 20px);

            }

            to {
                background-image: repeating-linear-gradient(135deg, rgba(0, 255, 0, .5) 0, rgba(0, 255, 0, .5) 10px, rgba(255, 255, 255, 0.5) 10px, rgba(255, 255, 255, 0.5) 20px),
                    repeating-linear-gradient(45deg, rgba(255, 255, 255, 0.5) 0, rgba(255, 255, 255, 0.5) 10px, rgba(0, 255, 0, .5) 10px, rgba(0, 255, 0, .5) 20px);

            }
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="box"></div>
    </div>

    <script>
        const box = document.querySelector('.box');
        const container = document.querySelector('.container');

        // 最大可移动范围
        let maxX = container.clientWidth - box.offsetWidth;
        // console.log(maxX);

        box.onmousedown = function (event) {
            let mouseBox = event.offsetX; // 短线段
            document.onmousemove = function (event) {
                let mouseClinet = event.clientX; // 长线段
                let x = mouseClinet - mouseBox - container.offsetLeft;
                if (x > maxX) {
                    x = maxX;
                }
                if (x < 0) {
                    x = 0;
                }
                box.style.cssText = `
                    left: ${x}px;
                `;
            }
            document.onmouseup = function () {
                document.onmousemove = null;
            }
        }
    </script>
</body>

</html>